class Solution
{
public:
    int subarraySum(vector<int> &nums, int k)
    {
        int n = nums.size();
        vector<int> preSum(n + 1, 0);
        int i;
        for (i = 1; i <= n; i++)
        {
            preSum[i] = preSum[i - 1] + nums[i - 1];
        }

        unordered_map<int, int> m;
        int ans = 0;
        for (i = 0; i <= n; i++)
        {
            int diff = preSum[i] - k;
            if (m.count(diff))
            {
                ans += m[diff];
            }
            m[preSum[i]] += 1;
        }
        return ans;
    }
};